package controller

import (
	"errors"
	"github.com/cy77cc/hioshop/models"
	"github.com/cy77cc/hioshop/utils"
	"github.com/gin-gonic/gin"
	"net/http"
)

type SettingHandler struct{}

func (SettingHandler) GetUserDetail(ctx *gin.Context) {
	id, exits := ctx.Get("id")
	res := utils.NewResponse()
	if !exits {
		res.SetRes(1, "id不存在", nil)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}

	userId := id.(uint)
	if userId <= 0 {
		res.SetRes(1, "请求参数错误", errors.New("错误"))
		ctx.JSON(http.StatusBadRequest, res)
		return
	}
	user := models.User{}
	user.ID = userId
	err := user.GetUserInfoById()
	if err != nil {
		res.SetRes(1, "请求参数错误", errors.New("错误"))
		ctx.JSON(http.StatusBadRequest, res)
		return
	}
	res.SetRes(0, "success", user)
	ctx.JSON(http.StatusOK, res)

}

func (SettingHandler) SaveUserInfo(ctx *gin.Context) {
	info := struct {
		Name     string `json:"name"`
		Avatar   string `json:"avatar"`
		Mobile   string `json:"mobile"`
		Nickname string `json:"nickName"`
	}{}
	res := utils.NewResponse()
	id, exists := ctx.Get("id")
	if !exists {
		res.SetRes(1, "id不存在", nil)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}
	userId := id.(uint)

	err := ctx.ShouldBind(&info)
	if err != nil {
		res.SetRes(1, "参数解析失败", nil)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}

	user := models.User{}
	user.ID = userId
	user.Avatar = info.Avatar
	user.Nickname = info.Nickname
	user.Name = info.Name
	user.Mobile = info.Mobile

	err = user.UpdateUserInfo()
	if err != nil {
		res.SetRes(1, "更新失败", nil)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}
	res.SetRes(0, "success", user)
	ctx.JSON(http.StatusOK, res)
}
